<?php 
if(KT!='KhiThe') exit;
class shoppingcarts_controller extends shoppingcarts_model{
	
	public function __construct(){
		global $lang;
		$this->_layout = NULL;
		$lang['sms']='';
		$this->lang = $lang;
		parent::__construct();
		parent::addObject('khithe_template');
		parent::addObject('khithe_request');
		parent::addObject('khithe_string');
		parent::addObject('khithe_images');
		parent::addObject('khithe_encryption');

	}
	
	public function index_action()
	{

		
		/*==================== View Cart =======================*/
		$strHtmlContent = $this->khithe_display('index');
		$this->arrBlockHtml = $this->khithe_getBlockHtml($strHtmlContent);

        $strHtmlContentM = $this->khithe_display('sendmail');
        $this->arrBlockHtmlM = $this->khithe_getBlockHtml($strHtmlContentM);

		$arrID = explode(',',$_SESSION['cart']);
		$contents = array();
		foreach ($arrID as $item) {
			$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
		}
		$arrRow = parent::selectProduct($arrID);
		$i=1; $Total_money=0;$resultHtml ='';$resultHtmlM ='';
		if(count($arrRow)){
			foreach ($arrRow as $row){
				$Price = $row['PriceSpecial']!=''?$row['PriceSpecial']/$this->lang["rate"]:$row['Price']/$this->lang["rate"];
				$Qty = $contents[$row['ID']];
				$TotalPQ = ($Price * $Qty);
				$Total_money = $Total_money +$TotalPQ;
				
				$arrCart = array(
					'stt'=>$i++,
					'cart_title'=>$row['Title'],
					'cart_price'=>number_format($Price,0,'.',','),
					'cart_count'=>$Qty,
					'cart_total'=>number_format($TotalPQ,0,'.',','),
					'cart_ID'=>$row['ID'],
				);
				
				$resultHtml .= $this->khithe_assign($this->arrBlockHtml['Cart'],$arrCart);
				$resultHtmlM .= $this->khithe_assign($this->arrBlockHtmlM['Cart'],$arrCart);

			}
			$this->lang['dis_sms'] = 'display:none';
		}else{
			$this->lang['style'] = 'display:none';
			$this->lang['dis_sms'] = '';
		}
		$this->lang['cart_total_money']=number_format($Total_money,0,'.',',');
		$strHtmlContent = $this->khithe_assignBlock($strHtmlContent, array('htmlCart'=>$resultHtml));
		$strHtmlContentM = $this->khithe_assignBlock($strHtmlContentM, array('htmlCart'=>$resultHtmlM));

		$this->lang['txt_Detail'] = isset($_POST['txt_Detail'])?$_POST['txt_Detail']:NULL;
		$this->lang['txt_usersValue'] =isset($_POST['txt_users'])?$_POST['txt_users']:NULL;
		$this->lang['txt_FullnameValue'] =isset($_POST['txt_Fullname'])?$_POST['txt_Fullname']:NULL;
		$this->lang['txt_PhoneValue'] =isset($_POST['txt_Phone'])?$_POST['txt_Phone']:NULL;
		$this->lang['txt_EmailValue'] =isset($_POST['txt_Email'])?$_POST['txt_Email']:NULL;
		$this->lang['txt_MobiValue'] =isset($_POST['txt_Mobi'])?$_POST['txt_Mobi']:NULL;
		$this->lang['txt_CMNDValue'] =isset($_POST['txt_CMND'])?$_POST['txt_CMND']:NULL;
		$this->lang['txt_AddressValue'] =isset($_POST['txt_Address'])?$_POST['txt_Address']:NULL;

        /*$this->lang['txt_Detail'] = isset($_POST['txt_Detail'])?$_POST['txt_Detail']:NULL;
		$this->lang['txt_usersValue'] =isset($_POST['txt_users'])?$_POST['txt_users']:$_SESSION['Username'];
		$this->lang['txt_FullnameValue'] =isset($_POST['txt_Fullname'])?$_POST['txt_Fullname']:$_SESSION['Fullname'];
		$this->lang['txt_PhoneValue'] =isset($_POST['txt_Phone'])?$_POST['txt_Phone']:$_SESSION['Phone'];
		$this->lang['txt_EmailValue'] =isset($_POST['txt_Email'])?$_POST['txt_Email']:$_SESSION['Email'];
		$this->lang['txt_MobiValue'] =isset($_POST['txt_Mobi'])?$_POST['txt_Mobi']:$_SESSION['Mobi'];
		$this->lang['txt_CMNDValue'] =isset($_POST['txt_CMND'])?$_POST['txt_CMND']:$_SESSION['CMND'];
		$this->lang['txt_AddressValue'] =isset($_POST['txt_Address'])?$_POST['txt_Address']:$_SESSION['Address'];*/

		$this->lang['only'] ='';
		
		$this->lang['active'] ='add';
		$this->lang['usersID'] ='';

		$strHtmlContent = $this->khithe_assign($strHtmlContent, $this->lang);


        /*==================== Save Cart =======================*/
        if(isset($_POST['txt_Fullname']) && $_SESSION['cart']!=''){

            if($_POST['txt_Fullname']=='') {
                $this->lang['sms'] = $this->lang['EmptyFullname'];

            }else if($_POST['txt_Sex']==''){
                $this->lang['sms'] = $this->lang['notEmptySex'];

            }else if($_POST['txt_Email']==''){
                $this->lang['sms'] = $this->lang['notEmptyEmail'];

            }else if($_POST['captcha']!=$_SESSION['Captcha'] || $_SESSION['Captcha']==''){
                $this->lang['sms'] = $this->lang['notEmptyCaptcha'];

            }else if($_POST['captcha']!=$_SESSION['Captcha'] || $_SESSION['Captcha']==''){
                $this->lang['sms'] = $this->lang['notEmptyCaptcha'];

            }else{

                $arrID = explode(',',$_SESSION['cart']);
                $arrCart = array();
                foreach ($arrID as $item) {
                    $arrCart[$item] = (isset($arrCart[$item])) ? $arrCart[$item] + 1 : 1;
                }
                $done =parent::insertCart($_POST,$arrCart);


                /* ----- Send Mail -------------------------*/
                if($_POST['txt_Email'])
                {
                    $order_id = $_SESSION['CartID'];
                    $Order_Code = 'TNB'.$_SESSION['TimeDate'].$order_id;
                    $day = 86400 * 5;
                    $time_ok = time() + $day;
                    $Order_Code_ok = $Order_Code.$time_ok;
                    $En_Code = $this->encrypt($Order_Code_ok);

                    $Bank = $_POST['txt_Bank'];
                    $this->lang['LinkBank'] = url_base . "shoppingcarts/checkout/$Bank/order/$Order_Code/$En_Code";
                    $strHtmlContentM = $this->khithe_assign($strHtmlContentM, $this->lang);

                    include (path_lib.'/mailer/phpmailer.php');
                    $mail = new mailer_phpmailer();
                    $title = 'Đơn Hàng của '. $_POST['txt_Fullname'];
                    $body = $strHtmlContentM;
                    $from_list = array(
                        array(
                            'name'=>'',
                            'email'=>trim($_POST['txt_Email'])
                        )
                    );
                    $bcc_list = array(
                        array(
                            'name'=>'',
                            'email'=>EmailShop
                        )
                    );
                    $mail->send_mail_g(EmailShop,NameShop,$from_list, $title, $body, $bcc_list);
                }

                /* //----- Send Mail -------------------------*/



                if($done){
                    $_SESSION['cart']=='';
                    unset($_SESSION['cart']);

                    $_SESSION['fullname'] = $_POST['txt_Fullname'];
                    $_SESSION['sex'] = $_POST['txt_Sex'];

                    $this->gotoload(url_base . 'shoppingcarts/checkout/'.$_POST['txt_Bank']);
                }
            }

        } /* End Save Cart */


		return $strHtmlContent;
		
	}
	
	
	public function checkout_action()
	{

		$cus_fullname = isset($_SESSION['fullname'])?$_SESSION['fullname']:NULL;
		$arr_cus_fullname = explode(' ',$cus_fullname);
		$this->lang['cus_fullname'] =  end($arr_cus_fullname);
		$this->lang['cus_sex'] = isset($_SESSION['sex'])&&$_SESSION['sex']==0?'Chị':($_SESSION['sex']==1?'Anh':' Anh/Chị ');
		
		$strHtmlContent = $this->khithe_display('checkout');
		$arrBlockHtml = $this->khithe_getBlockHtml($strHtmlContent);

        $time_ok = time();
		
		
		switch ($this->valUrl(1))
		{
			case 'nganluong':
				require_once(path_base.'/library/payment/nganluong/lib/nusoap.php');
				require_once(path_base.'/library/payment/nganluong/nganluong.microcheckout.class.php');
		
				if($this->valUrl(2)=='ok')
				{
					$order_id = substr($this->valUrl(3), 11);
					$order_code = $this->valUrl(3);
					$this->setCartOk(intval($order_id));
					$this->gotoload(url_base);
					exit();
					
				}else if($this->valUrl(2)=='order')
				{
					$order_id = substr($this->valUrl(3), 11);
					$order_code = $this->valUrl(3);
                    $order_code_ok = $this->decrypt($this->valUrl(4));
                    if($order_code_ok <= $order_code.''.$time_ok) exit();
					
				}else{
				
					$order_id = $_SESSION['CartID'];
					$order_code = 'TNB'.$_SESSION['TimeDate'].$order_id;
				
				}
				
				$link_payment = '';
				$items = $this->getCartIDNganLuong($order_id);
				$amount = $this->getSumPriceCart($order_id);
				$return_url = url_base . 'shoppingcarts/checkout/nganluong/ok/'.$order_code;
				$cancel_url = url_base;	
				 
				$inputs = array(
					'receiver' => RECEIVER ,
					'order_code' => $order_code,
					'amount' => $amount ,
					'currency_code' => 'vnd' ,
					'tax_amount' => '0' ,
					'discount_amount' => '0' ,
					'fee_shipping' => '0' ,
					'request_confirm_shipping' => '0' , 
					'no_shipping' => '1' , 
					'return_url' => $return_url ,
					'cancel_url' => $cancel_url ,
					'language' => 'vn' ,
					'items' => $items 
				);

				$obj = new NL_MicroCheckout( MERCHANT_ID , MERCHANT_PASS , URL_WS );
				$result = $obj->setExpressCheckoutPayment( $inputs );
				
				if ( $result != false && $result[ 'result_code' ] == '00' ) {
	
					$link_payment = trim( $result[ 'link_checkout' ] );
					
				}
				else {
					$this->gotoload($cancel_url);
				}
				
				$this->lang['link_payment'] =  $link_payment;
				$resultHtml = $this->khithe_assign($arrBlockHtml['nganluong'],$this->lang);
				
			break;
			
			case 'baokim':
				require_once(path_base.'/library/payment/BaoKimPayment.php');
				if($this->valUrl(2)=='ok')
				{
					$order_id = substr($this->valUrl(3), 11);
					$order_code = $this->valUrl(3);
					$this->setCartOk(intval($order_id));
					$this->gotoload(url_base);
					exit();
				}else if($this->valUrl(2)=='order')
				{
					$order_id = substr($this->valUrl(3), 11);
					$order_code = $this->valUrl(3);

                    $order_code_ok = $this->decrypt($this->valUrl(4));
                    if($order_code_ok <= $order_code.''.$time_ok) exit();

				}else{
					$order_id = $_SESSION['CartID'];
					$order_code = 'TNB'.$_SESSION['TimeDate'].$order_id;
				}
								
                $business = RECEIVER;
				$total_amount = $this->getSumPriceCart($order_id);
				$shipping_fee = 0;
				$tax_fee = 0;
				$order_description = 'ThuNhoiBong.Net';

				$url_success = url_base . 'shoppingcarts/checkout/nganluong/ok/'.$order_code;
				$url_cancel = url_base;
				$url_detail = url_base . 'shoppingcarts/checkout/nganluong/ok/'.$order_code;
				$bk = new BaoKimPayment();
				$link_payment = trim( $bk->createRequestUrl( $order_code , $business , $total_amount , $shipping_fee , $tax_fee , $order_description , $url_success , $url_cancel , $url_detail ) );

				$this->lang['link_payment'] =  $link_payment;
				$resultHtml = $this->khithe_assign($arrBlockHtml['baokim'],$this->lang);
			break;
			
			
			case 'cardphone':
				$this->lang['link_payment'] =  $link_payment;
				$resultHtml = $this->khithe_assign($arrBlockHtml['cardphone'],$this->lang);
			break;


			case 'bank':
				if($this->valUrl(2)=='order')
				{
					$order_id = substr($this->valUrl(3), 11);
					$order_code = $this->valUrl(3);
                    $order_code_ok = $this->decrypt($this->valUrl(4));
                    if($order_code_ok !=$order_code.''.$time_ok) exit();
				}else{
					$order_id = $_SESSION['CartID'];
					$order_code = 'TNB'.$_SESSION['TimeDate'].$order_id;
				} 
				
				$this->lang['link_payment'] =  $link_payment;
				$resultHtml = $this->khithe_assign($arrBlockHtml['bank'],$this->lang);
			break;
			
			
			default:
				if($this->valUrl(2)=='order')
				{
					$order_id = substr($this->valUrl(3), 11);
					$order_code = $this->valUrl(3);
                    $order_code_ok = $this->decrypt($this->valUrl(4));
                    if($order_code_ok <= $order_code.''.$time_ok) exit();

				}else{
					$order_id = $_SESSION['CartID'];
					$order_code = 'TNB'.$_SESSION['TimeDate'].$order_id;
				}
				
				$this->lang['link_payment'] =  $link_payment;
				$resultHtml = $this->khithe_assign($arrBlockHtml['office'],$this->lang);
			break;
		}
		
		$sumprice = $this->getSumPriceCart(intval($order_id));
		$this->lang['cus_total'] = empty($sumprice)?'0 VNĐ':number_format($sumprice, 0, '.', ',').' VNĐ';
		
		$this->lang['order_code'] =  $order_code;
		$strHtmlContent = $this->khithe_assignBlock($strHtmlContent, array('htmlcart'=>$resultHtml));
		
		$strHtmlContent = $this->khithe_assign($strHtmlContent,$this->lang);
		return $strHtmlContent;
	} 
	
	
	public function add_action()
	{
		if (isset($_SESSION['cart']) && $this->valUrl(1)!=0 && $this->valUrl(1)!='') {
					$_SESSION['cart'] .= ','.intval($this->valUrl(1));
		} else {
			$_SESSION['cart'] = intval($this->valUrl(1));
		}
		$this->gotoload(url_base.'shoppingcarts');
	}
	
	public function addAjax_action()
	{
		$this->_layout = 'NOT';
				
		if (isset($_SESSION['cart']) && $this->valUrl(1)!=0 && $this->valUrl(1)!='') {
					$_SESSION['cart'] .= ','.intval($this->valUrl(1));
		} else {
			$_SESSION['cart'] = intval($this->valUrl(1));
		}
		echo $_SESSION['cart'];exit();
		return null;
	}
	
	public function addupdate_action()
	{
		$this->_layout = 'NOT';
		if (isset($_SESSION['cart'])) {
			$items = explode(',',$_SESSION['cart']);
			$newcart = '';
			foreach ($items as $item) {
				if ($this->valUrl(1) != $item) {
					if ($newcart != '') {
						$newcart .= ','.$item;
					} else {
						$newcart = $item;
					}
				}
			}
			$_SESSION['cart'] = $newcart;
		}
		
		if($this->valUrl(2)){
			$_SESSION['cart'] .= str_repeat(',' . intval($this->valUrl(1)),intval($this->valUrl(2)));
		}
		
		echo $_SESSION['cart'];exit();
		return null;
	}
	
	public function update_action()
	{
		if (isset($_SESSION['cart'])) {
			$newcart = '';
			
			foreach ($_POST as $key=>$value) {
				if (stristr($key,'qty')) {
					$id = str_replace('qty','',$key);
					$id = intval($id);
					$items = ($newcart != '') ? explode(',',$newcart) : explode(',',$_SESSION['cart']);
					$newcart = '';
					foreach ($items as $item) {
						if ($id != $item) {
							if ($newcart != '') {
								$newcart .= ','.$item;
							} else {
								$newcart = $item;
							}
						}
					}
					for ($i=1;$i<=$value;$i++) {
						if ($newcart != '') {
							$newcart .= ','.$id;
						} else {
							$newcart = $id;
						}
					}
				}
			}
		}
		$_SESSION['cart'] = $newcart;
		$this->gotoload(url_base.'shoppingcarts');
		
	}
	
	public function delete_action()
	{
		if (isset($_SESSION['cart'])) {
			$items = explode(',',$_SESSION['cart']);
			$newcart = '';
			foreach ($items as $item) {
				if ($this->valUrl(1) != $item) {
					if ($newcart != '') {
						$newcart .= ','.$item;
					} else {
						$newcart = $item;
					}
				}
			}
			$_SESSION['cart'] = $newcart;
		}
		$this->gotoload(url_base.'shoppingcarts');
	}
	
	public function index_ajax_action()
	{
		
	}


}
?>